<?php

namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\Activity;
use App\Models\Area;
use Illuminate\Http\Request;

class AreaController extends Controller
{
    public function areaList($search = ""){
        if($search != ''){
            $areas = Area::where('name', 'like', '%'.$search.'%')->paginate(6);
        }else{
            $areas = Area::paginate(6);
        }
	//print_r($areas);
        return view('admin.area',['items'=>$areas,'type'=>'list','searchWord'=>$search]);
    }
    public function areaHandler($type,$id = ''){
        $allActivity = Activity::paginate(6);
        if ($type == 'add'){
            if ($id != ''){
                return redirect('/admin/area/edit/'.$id);
            }
            return view('admin.area',['type'=>$type,'id'=>'new','activity_id'=>'','allActivity'=>$allActivity]);
        }else if($type == 'edit'){
            if ($id == ''){
                return redirect('/admin/area/add');
            }
            $area = Area::findOrFail($id);
            return view('admin.area',['type'=>$type,'id'=>$id,'name'=>$area->name,'intro'=>$area->intro,
                'cover'=>$area->cover,'activity_id'=>$area->activity_id,'allActivity'=>$allActivity]);
        }else{
            abort('404');
        }
    }

    public function saveArea(Request $request){
        $id = $request['id'];
        $activity_id = $request['activity_id'];
        $cover = $request['cover'];
        $name = $request['name'];
        $intro = $request['intro'];
        if ($id == 'new'){
            $area = new Area();
        }else{
            $area = Area::findOrFail($id);
        }
        $area->name = $name;
        $area->cover = $cover;
        $area->intro = $intro;
        $area->activity_id=$activity_id;
        $area->save();
        return response()->json(['res'=>true,'msg'=>'保存成功']);
    }

    public function deleteArea(Request $request){
        $id = $request['id'];
        Area::find($id)->delete();
        return response()->json(['res'=>true,'msg'=>'删除成功']);
    }
}
